package com.woniuxy.thred;

/**
 * description: Racer <br>
 * date: 2022/2/5 2:06 上午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

import java.util.concurrent.*;

/**
 * 模拟龟兔赛跑
 */
public class CRacer implements Callable<Integer> {
    //胜利者名称
    private static String winner;

    @Override
    public Integer call() throws Exception {
        for (int steps = 1; steps <= 100; steps++) {
            //模拟休息
            if (Thread.currentThread().getName().equals("兔子") && steps % 10 == 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "-->" + steps);
            //判断是否结束了
            boolean flag = gameOver(steps);
            if (flag) {
                return steps;
            }
        }
        return null;
    }

    private boolean gameOver(int steps) {
        if (winner != null) {
            //存在胜利者了
            return true;
        } else {
            if (steps == 100) {
                winner = Thread.currentThread().getName();
                System.out.println("winner=>" + winner);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CRacer racer = new CRacer();
        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(2);
        //提交执行
        Future<Integer> result1 = ser.submit(racer);
        Future<Integer> result2 = ser.submit(racer);

        //获取结果
        Integer r1 = result1.get();
        Integer r2 = result1.get();
        System.out.println(r2);
        //关闭服务
        ser.shutdown();
    }
}
